<template>
  <view class="page">
    <demo-block title="栗子海报">
      <l-painter @fail="fail" @done="done" pathType="url" ref="poster" performance css="position:relative;">
        <l-painter-image :src="props.bgImg" css="width:100vw;height:700px;" />
        <l-painter-image :src="props.info" :css="`object-fit: cover;width:90px;height:90px;position:absolute;left:50%;bottom:${props.qrCodeBottom}px; transform: translateX(-50%);`" />
      </l-painter>
    </demo-block>
  </view>
</template>

<script lang="ts" setup>
import { BASE_UPLOADURL } from "@/utils/request";
import { ref } from "vue";
const props = defineProps<{
  info: string;
  bgImg: string;
  qrCodeBottom: string;
}>();
const poster = ref();
const picture = ref("");
const fail = () => {};
const done = () => {
  console.log("绘制完成:");
};
const save = () => {
  uni.showLoading({
    title: "海报加载中",
  });
  setTimeout(() => {
    poster.value.canvasToTempFilePath({
      fileType: "jpg",
      quality: 1,
      width: 300,
      height: 500,
      success: (res: any) => {
        console.log(res.tempFilePath);
        uni.uploadFile({
          url: BASE_UPLOADURL, //仅为示例，非真实的接口地址
          filePath: res.tempFilePath,
          name: "file",
          header: {
            Authorization: uni.getStorageSync("token"),
          },
          success: (uploadFileRes) => {
            console.log(uploadFileRes, "uploadFileRes");
            if (!uploadFileRes.data) {
              uni.hideLoading();
              uni.showToast({
                title: "海报生成失败",
                icon: "none",
              });
            }
            picture.value = JSON.parse(uploadFileRes.data).data;
            // saveImage();
            setTimeout(() => {
              shareImg();
            }, 200);
          },
        });
      },
      fail(e: any) {
        console.log("???????????", e);
      },
    });
  }, 700);
};
const shareImg = () => {
  uni.downloadFile({
    url: picture.value, //分享的图片的链接
    success: (res) => {
      console.log(res);
      uni.showShareImageMenu({
        path: res.tempFilePath,
        complete() {
          setTimeout(() => {
            uni.hideLoading();
          }, 300);
        },
      });
    },
    complete() {
      //隐藏loading
      uni.hideLoading();
    },
    fail(err) {
      console.log(err, "shareImg");
    },
  });
};
// 保存图征
const saveImage = () => {
  uni.saveImageToPhotosAlbum({
    filePath: picture.value,
    success(res) {
      uni.showToast({
        title: "已保存到相册",
        icon: "success",
        duration: 2000,
      });
    },
    fail(err) {
      console.log(err);
    },
  });
};
defineExpose({
  save,
});
</script>
<style>
.page {
  position: absolute;
  left: -999px;
  top: -999px;
}
</style>
